package com.jushu.storbox.view.viewImpl;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.widget.TextView;

import com.jushu.storbox.R;

public class ITextView extends TextView {

	private String mText;
	private Paint mPaint;
	private String[] mTexts;
	private String mCurrentText;

	public ITextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
		TypedArray a = context.obtainStyledAttributes(attrs,  
			                R.styleable.iTextView);  
			         
		  int textColor = a.getColor(R.styleable.iTextView_textColor,  
		               0XFFFFFFFF);  
	      float textSize = a.getDimension(R.styleable.iTextView_textSize, 22);
	     mText = a.getString(R.styleable.iTextView_text);
	     mPaint.setColor(textColor);
	     mPaint.setTextSize(textSize);
	}

	public ITextView(Context context) {
		super(context);
		initPaint();
	}



	public ITextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initPaint();
	}

	private void initPaint() {
		mPaint = getPaint();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		// super.onDraw(canvas);
		FontMetrics fm = mPaint.getFontMetrics();

		float baseline = fm.descent - fm.ascent;
		float x = 0;
		float y = baseline;
		for (String text : mTexts) {
			canvas.drawText(text, x, y, mPaint); 
			y += baseline + fm.leading + 5; 
		}

	}

	/**
	 * @param content
	 * @param p
	 * @param width
	 * @return
	 */
	private String[] autoSplit(String content, Paint p, float width) {
		int length = content.length();
		float textWidth = p.measureText(content);
		if (content == null || content.trim().equals("")) {
			return null;
		}
		if (textWidth <= width) {
			return new String[] { content };
		}

		int start = 0, end = 1, i = 0;
		int lines = (int) Math.ceil(textWidth / (width -5)); 
		String[] lineTexts = new String[lines];
		while (start < length) {
			if ((p.measureText(content, start, end) ) > width -5) {
				lineTexts[i++] = (String) content.subSequence(start, end);
				start = end;
			}
			if (end == length) {
				lineTexts[i] = (String) content.subSequence(start, end);
				break;
			}
			end += 1;
		}
		return lineTexts;
	}

	private String[] getAutoSplit(String content, Paint p, float width) {
		ArrayList<String> result = new ArrayList<String>();
		String[] texts = content.split("\\n");
		for (String text : texts) {
			String[] strs = autoSplit(stringFilter(toDBC(text)), p, width);
			if (strs != null) {
				for (String str : strs) {
					result.add(str);
				}
			}
		}
		String[] strResult = new String[result.size()];
		for (int i = 0; i < result.size(); i++) {
			strResult[i] = result.get(i);
		}
		return strResult;
	}

	/**
	 * @param input
	 * @return
	 */
	public String toDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	/**
	 * @param str
	 * @return
	 */
	public String stringFilter(String str) {
		str = str.replaceAll("【", "[").replaceAll("】", "]")
				.replaceAll("！", "!").replaceAll("：", ":");
		String regEx = "[『』]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public void setIText(CharSequence text) {
		// mText = toDBC(text.toString());
		mText = text.toString();
	}

	@Override
	public CharSequence getText() {
		// TODO Auto-generated method stub
		return mText;
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
	
	@Override
	public void draw(Canvas canvas) {
		
		mPaint.setColor(getCurrentTextColor());
		FontMetrics fm = mPaint.getFontMetrics();

		float baseline = fm.descent - fm.ascent;

		if (mTexts == null || mCurrentText != mText) {
			mTexts = getAutoSplit(getText().toString(), mPaint, getWidth() - 5);
			int height = (int) ((baseline + 5) * mTexts.length) + 10;
			int mesSpecHeight = MeasureSpec.makeMeasureSpec(height,
					MeasureSpec.EXACTLY);
			measure(getMeasuredWidth(), mesSpecHeight);
			setHeight(height);
			mCurrentText = mText;
		}

		super.draw(canvas);
	}

}
